package com.castlzl.random.core.uid;

import com.castlzl.random.core.IdGenerator;
import lombok.Getter;

/**
 * 基于百度UidGenerator的实现
 * 优化的雪花算法，提供更好的时钟回拨处理
 * @author leiziliang
 */
public class UidGenerator implements IdGenerator {

    /**
     * 起始时间：2023-01-01 00:00:00
     */
    private final static long START_TIMESTAMP = 1672531200000L;

    private final static long WORKER_ID_BITS = 16L;
    private final static long SEQUENCE_BITS = 7L;

    private final static long MAX_WORKER_ID = ~(-1L << WORKER_ID_BITS);
    private final static long SEQUENCE_MASK = ~(-1L << SEQUENCE_BITS);

    private final static long WORKER_ID_SHIFT = SEQUENCE_BITS;
    private final static long TIMESTAMP_LEFT_SHIFT = WORKER_ID_BITS + SEQUENCE_BITS;

    @Getter
    private final long workerId;

    private long sequence = 0L;
    private long lastTimestamp = -1L;

    // 时钟回拨最大容忍度(毫秒)
    private final long maxBackwardMillis = 3000L;
    // 上次时钟回拨的时间戳
    private long lastBackwardTimestamp = 0L;

    public UidGenerator(long workerId) {
        if (workerId > MAX_WORKER_ID || workerId < 0) {
            throw new IllegalArgumentException(String.format("Worker Id can't be greater than %d or less than 0", MAX_WORKER_ID));
        }
        this.workerId = workerId;
    }

    @Override
    public synchronized long nextId() {
        long timestamp = timeGen();

        // 时钟回拨检查和处理
        if (timestamp < lastTimestamp) {
            long backwardMillis = lastTimestamp - timestamp;
            
            // 如果回拨时间在容忍范围内，且距离上次回拨已经足够长，则允许等待
            if (backwardMillis <= maxBackwardMillis 
                    && timestamp - lastBackwardTimestamp > maxBackwardMillis * 2) {
                try {
                    Thread.sleep(backwardMillis);
                    timestamp = timeGen();
                    lastBackwardTimestamp = timestamp;
                } catch (InterruptedException e) {
                    Thread.currentThread().interrupt();
                    throw new RuntimeException("Thread interrupted when waiting for clock moving forward");
                }
            } else {
                throw new RuntimeException(String.format(
                        "Clock moved backwards. Refusing to generate id for %d milliseconds", backwardMillis));
            }
        }

        if (lastTimestamp == timestamp) {
            sequence = (sequence + 1) & SEQUENCE_MASK;
            if (sequence == 0) {
                timestamp = tilNextMillis(lastTimestamp);
            }
        } else {
            sequence = 0L;
        }

        lastTimestamp = timestamp;

        return ((timestamp - START_TIMESTAMP) << TIMESTAMP_LEFT_SHIFT)
                | (workerId << WORKER_ID_SHIFT)
                | sequence;
    }

    protected long tilNextMillis(long lastTimestamp) {
        long timestamp = timeGen();
        while (timestamp <= lastTimestamp) {
            timestamp = timeGen();
        }
        return timestamp;
    }

    protected long timeGen() {
        return System.currentTimeMillis();
    }

    @Override
    public String getName() {
        return "uid";
    }
}